package com.commerce.product.exception;

import com.commerce.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理秒杀相关异常
     */
    @ExceptionHandler(FlashSaleException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> handleFlashSaleException(FlashSaleException e, HttpServletRequest request) {
        log.warn("秒杀异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleValidationException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.warn("参数校验异常: {} - {}", request.getRequestURI(), e.getMessage());
        
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        return Result.error(400, "参数校验失败");
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleBindException(BindException e, HttpServletRequest request) {
        log.warn("参数绑定异常: {} - {}", request.getRequestURI(), e.getMessage());
        
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        return Result.error(400, "参数绑定失败");
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        log.warn("参数类型异常: {} - {}", request.getRequestURI(), e.getMessage());
        String message = String.format("参数 '%s' 类型错误，期望类型: %s", 
            e.getName(), e.getRequiredType().getSimpleName());
        return Result.error(400, message);
    }

    /**
     * 处理限流异常
     */
    @ExceptionHandler(RateLimitException.class)
    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public Result<Object> handleRateLimitException(RateLimitException e, HttpServletRequest request) {
        log.warn("限流异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(429, "请求过于频繁，请稍后再试");
    }

    /**
     * 处理库存不足异常
     */
    @ExceptionHandler(StockInsufficientException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> handleStockInsufficientException(StockInsufficientException e, HttpServletRequest request) {
        log.warn("库存不足异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(1001, "商品库存不足，请选择其他商品");
    }

    /**
     * 处理用户被封禁异常
     */
    @ExceptionHandler(UserBannedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<Object> handleUserBannedException(UserBannedException e, HttpServletRequest request) {
        log.warn("用户被封禁: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(403, "账号异常，请联系客服");
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, "系统繁忙，请稍后再试");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, "系统异常，请稍后再试");
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, "系统数据异常，请稍后再试");
    }

    /**
     * 处理数组越界异常
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleIndexOutOfBoundsException(IndexOutOfBoundsException e, HttpServletRequest request) {
        log.error("数组越界异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, "系统数据异常，请稍后再试");
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.warn("非法参数异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(400, "参数错误: " + e.getMessage());
    }

    /**
     * 处理非法状态异常
     */
    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public Result<Object> handleIllegalStateException(IllegalStateException e, HttpServletRequest request) {
        log.warn("非法状态异常: {} - {}", request.getRequestURI(), e.getMessage());
        return Result.error(409, "操作冲突: " + e.getMessage());
    }
}

/**
 * 业务异常基类
 */
class BusinessException extends RuntimeException {
    private final int code;

    public BusinessException(int code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message) {
        super(message);
        this.code = 500;
    }

    public int getCode() {
        return code;
    }
}

/**
 * 秒杀异常
 */
class FlashSaleException extends BusinessException {
    public FlashSaleException(String message) {
        super(1000, message);
    }

    public FlashSaleException(int code, String message) {
        super(code, message);
    }
}

/**
 * 限流异常
 */
class RateLimitException extends BusinessException {
    public RateLimitException(String message) {
        super(429, message);
    }
}

/**
 * 库存不足异常
 */
class StockInsufficientException extends BusinessException {
    public StockInsufficientException(String message) {
        super(1001, message);
    }
}

/**
 * 用户被封禁异常
 */
class UserBannedException extends BusinessException {
    public UserBannedException(String message) {
        super(403, message);
    }
}
